package com.hy.study.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Objects;

/**
 * @author huyong
 * @date 2024 年 01 月 09 日 11:05: 06
 */
@Controller
@Scope("prototype")
@Slf4j
public class FileController {

    @GetMapping(path = "file")
    public String file() {
        log.info("跳转到文件上传页面");
        return "file";
    }

    @PostMapping(path = "upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(new File(file.getOriginalFilename()).toPath()));
        log.info("文件名为:{}", file.getOriginalFilename());
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();
        return "upload File successfully";
    }

    @GetMapping(value = "/multifileupload")
    public String multiFile() {
        log.info("跳转多文件上传");
        return "multiFile";
    }

    @ResponseBody
    @PostMapping(value = "multiFileUpload")
    public String update(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartHttpServletRequest.getFiles("file");
        for (MultipartFile multipartFile : files) {
            try {
                BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(Objects.requireNonNull(multipartFile.getOriginalFilename())));
                outputStream.write(multipartFile.getBytes());
                outputStream.flush();
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "文件上传失败";
            } catch (IOException e) {
                e.printStackTrace();
                return "文件上传失败";
            }
        }
        return "文件上传成功";
    }
}
